package zerocopy;

import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * disk-disk零拷贝
 */
//@SpringBootApplication
public class ZerocopyFile {
    private static final Logger logger = LoggerFactory.getLogger(ZerocopyFile.class);

    @SuppressWarnings("resource")
    public static void transferToDemo(String from, String to) throws IOException {
        FileChannel fromChannel = new RandomAccessFile(from, "rw").getChannel();
        FileChannel toChannel = new RandomAccessFile(to, "rw").getChannel();

        long position = 0;
        long count = fromChannel.size();

        fromChannel.transferTo(position, count, toChannel);

        fromChannel.close();
        toChannel.close();
    }

    @SuppressWarnings("resource")
    public static void transferFromDemo(String from, String to) throws IOException {
        FileChannel fromChannel = new FileInputStream(from).getChannel();
        FileChannel toChannel = new FileOutputStream(to).getChannel();

        long position = 0;
        long count = fromChannel.size();

        toChannel.transferFrom(fromChannel, position, count);

        fromChannel.close();
        toChannel.close();
    }

    public static void copyDemo(String from, String to) throws IOException {
        Files.copy(new java.io.File(from),new java.io.File(to));
    }

//    public static void copyDemo(String from,String to)
//            throws IOException {
//        InputStream input = null;
//        OutputStream output = null;
//        try {
//            input = new FileInputStream(new File(from));
//            output = new FileOutputStream(new File(to));
//            byte[] buf = new byte[1024];
//            int bytesRead;
//            while ((bytesRead = input.read(buf)) > 0) {
//                output.write(buf, 0, bytesRead);
//            }
//        } finally {
//            input.close();
//            output.close();
//        }
//    }

    public static void main(String[] args) throws IOException {
        String from = "/opt/1.data";
        String to = "/opt/2.data";

        logger.info("begin io");
        copyDemo(from, to);
        logger.info("end io");

        logger.info("begin nio");
        transferFromDemo(from, to);
        logger.info("end nio");

    }
}